

package org.ring.rpc;


import org.ring.common.utils.reflect.MethodDescriptor;
import org.ring.common.utils.reflect.ServiceDescriptor;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @since 2024-10-28 19:15
 */
public class JDKProxyFactory implements ProxyFactory{

    private ServiceRepository serviceRepository = ServiceRepository.getInstance();

    public <T> T getProxy(Invoker<T> invoker, Class<?>[] interfaces){
        return (T)Proxy.newProxyInstance(invoker.getClass().getClassLoader(), interfaces, new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                Invocation invocation = new Invocation();
                invocation.setInterfaceName(method.getDeclaringClass().getName());
                invocation.setMethodName(method.getName());
                ServiceDescriptor serviceDescriptor = serviceRepository.lookup(method.getDeclaringClass().getName());
                MethodDescriptor methodDescriptor = serviceDescriptor.getMethod(method);
                invocation.setParamDescriptor(methodDescriptor.getParameterDescriptor());
                invocation.setArgs(args);
                return invoker.invoke(invocation);
            }
        });
    }

}
